package com.itwn.springcloud.controller;

import com.itwn.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystrixController {

    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/paymentInfo_OK/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id){
        String s = paymentHystrixService.paymentInfo_OK(id);
        return s;
    }

    /**
     * 模拟报错环境   1.超时兜底  2.计算异常兜底
     *
     *  方案一:
     *      1.主启动类添加激活@EnableHystrix
     *
     *      2.方法上添加@HystrixCommand
     *      paymentInfo_TimeOut     TimeUnit.SECONDS.sleep(5)设置反应时间5秒
     *
     *      fallbackMethod      失败后的,兜底方法
     *      HystrixProperty     线程超时时间  value=3  要求时间3秒
     *
     * @param id
     * @return
     */
    @GetMapping("/consumer/payment/hystrix/paymentInfo_TimeOut/{id}")
//    @HystrixCommand(fallbackMethod = "paymentInfo_ConsumerTimeOutHandler",commandProperties = {
//            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="6000")
//    })
    @HystrixCommand
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id){
        int num=10/0;
        String s = paymentHystrixService.paymentInfo_TimeOut(id);
        return s;
    }

    public String paymentInfo_ConsumerTimeOutHandler(@PathVariable("id") Integer id){
        return "线程池" + Thread.currentThread().getName() +" paymentInfo_ConsumerTimeOutHandler系统忙,请稍后重试! : id "+id +"\t"+"o(╥﹏╥)o";
    }

    //通用的fallback
    public String payment_Global_FallbackMethod(){
        return "payment_Global_FallbackMethod 异常处理信息,请稍后重试!";
    }

}
